<template>
	<view class="user-profile-page">
		<!-- 顶部背景与用户信息 -->
		<view class="profile-header">
			<view class="header-bg" :style="{ backgroundImage: 'url(' + (userInfo.bgPic ? userInfo.bgPic.url : defaultBg) + ')' }"></view>
			<view class="user-info-container">
				<view class="nicpic" @click="viewLargeAvatar">
					<image class="pic" v-if="userInfo.nicPic" :src="userInfo.nicPic" mode="aspectFill" lazy-load></image>
					<avatar-fallback :size="75" v-else :name="userInfo.nicName"></avatar-fallback>
				</view>
				<view class="name-area">
					<view class="name-row">
						<text class="name" v-if="remark">{{remark}}</text>
						<text class="name" v-else>{{ userInfo.nicName || '匿名用户' }}</text>
						<view class="friend-badge" v-if="isFriend">
							<text class="badge-text">好友</text>
						</view>
					</view>
					<view class="userid">ID: {{ userInfo.userId || '未知' }}</view>
					<view class="user-signature" v-if="userInfo.signature">
						<text>{{ userInfo.signature }}</text>
					</view>
				</view>
				<view class="remark-name" @click="remarkName">
					<uni-icons type='compose'></uni-icons>
					<text>备注名</text>
				</view>
			</view>
		</view>

		<!-- 统计数据 -->
		<view class="stats-container">
			<view class="stat-item" @click="navigateTo('shops')">
				<text class="stat-value">{{ shopInfo.length }}</text>
				<text class="stat-label">店铺</text>
			</view>
			<view class="stat-item" @click="navigateTo('goods')">
				<text class="stat-value">{{ goodInfo.length }}</text>
				<text class="stat-label">商品</text>
			</view>
			<view class="stat-item" @click="navigateTo('fans')">
				<text class="stat-value">{{ userInfo.fansCount || 0 }}</text>
				<text class="stat-label">粉丝</text>
			</view>
		</view>

		<!-- 店铺信息 -->
		<view class="section shopInfo">
			<view class="section-header">
				<text class="section-title">店铺</text>
				<text class="section-more" v-if="shopInfo.length > 0" @click="navigateTo('allShops')">查看全部</text>
			</view>

			<view class="empty-state" v-if="shopInfo.length === 0">
				<uni-icons type="shop" size="48" color="#55aaff" />
				<text class="empty-text">还没有店铺</text>
			</view>

			<scroll-view scroll-x="true" class="horizontal-scroll" v-else>
				<view class="scroll-container">
					<view class="shop-item" v-for="(shop, index) in shopInfo" :key="index" @click="viewShopDetail(shop)">
						<image class="shop-img" :src="shop.photos[0].url || defaultShopPic" mode="aspectFill" lazy-load></image>
						<text class="shop-name">{{ shop.title }}</text>
						<text class="shop-desc">{{ shop.district || '暂无描述' }}</text>
						<view class="shop-sendInfo">
							<view class="">
								<uni-icons type="location" color="#55aaff" size="18"></uni-icons>
								<text>{{ getDistance(shop.location) }}</text>
							</view>
							<view class="">
								<uni-icons type="calendar" color="#55aaff" size="18"></uni-icons>
								<text>{{ formatMessageTime(shop.sendTime) }}</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 商品信息 -->
		<view class="section goodInfo">
			<view class="section-header">
				<text class="section-title">商品</text>
				<text class="section-more" v-if="goodInfo.length > 0" @click="navigateTo('allGoods')">查看全部</text>
			</view>

			<view class="empty-state" v-if="goodInfo.length === 0">
				<uni-icons type="goods" size="48" color="#ccc" />
				<text class="empty-text">还没有商品信息</text>
			</view>

			<scroll-view scroll-x="true" class="horizontal-scroll" v-else>
				<view class="scroll-container">
					<view class="good-item" v-for="(good, index) in goodInfo" :key="index" @click="viewGoodDetail(good)">
						<image class="good-img" :src="good.images[0].url || defaultGoodPic" mode="aspectFill" lazy-load></image>
						<text class="good-name">{{ good.title }}</text>
						<text class="good-price">¥{{ good.price.toFixed(2) }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 操作按钮区域 -->
		<view class="btnarea">
			<view class="action-btn add-friend" v-if="status !== 1" @click="handleAddFriend" :class="{ loading: addFriendLoading }">
				<uni-icons type="personadd" size="20" color="#fff" v-if="!addFriendLoading" />
				<uni-loading size="20" color="#fff" v-if="addFriendLoading" />
				<text class="btn-text">添加好友</text>
			</view>
			<view class="action-btn has-friend" v-if="isFriend === 1">
				<uni-icons type="contact" size="20" color="#fff" />
				<text class="btn-text">已为好友</text>
			</view>
			<view class="action-btn message" @click="handleSendMessage" :disabled="status !== 1" :class="{ disabled: status !== 1 }">
				<uni-icons type="chat" size="20" color="#fff" />
				<text class="btn-text">发私聊</text>
			</view>
		</view>
		<input-dialog
			:isShow.sync="isDialogShow"
			:initialValue="applyMsg"
			:title="title"
			:maxlength="maxLength"
			@confirm="applyConfirm"
			@cancel="applyCancel"
			:placeholder="placeholder"
		></input-dialog>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
import formatMessageTime from '../../utils/formatMessageTime';
import { distance_m } from '../../utils/distance';
import { handleFriendRelation } from '@/utils/friend.js';
import setToTarget from '../../utils/setTarget';
const friend = uniCloud.importObject('friend', { customUI: true });
import InputDialog from '../../components/InputDialog.vue';
import MessageSender from '../../utils/MessageSender';
import AvatarFallback from '../../components/AvatarFallback.vue';

import getFriendUserInfo from '../../utils/getFriendUserInfo';

export default {
	components: {
		InputDialog,
		AvatarFallback
	},
	data() {
		return {
			userInfo: {},
			shopInfo: [],
			goodInfo: [],
			remark:"",
			isDialogShow: false,
			markerId: '', // 从路由参数获取的用户ID
			addFriendLoading: false,
			toastMessage: '',
			isFriend: false,
			placeholder:"",
			applyMsg: '',
			type:"",
			status: 4,
			maxLength:200,
			title:"",
			// 默认图片
			defaultAvatar: '/static/nicPic/m2.png',
			defaultBg: '/static/bgpic.png',
			defaultShopPic: '/static/images/default-shop.png',
			defaultGoodPic: '/static/images/default-good.png',
			statusMap: {
				0: '已发送申请',
				1: '已是好友',
				2: '已拉黑',
				3: '已删除',
				4: '添加好友'
			}
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		}
	},

	onLoad(res) {
		this.markerId = res.id;
		this.getIsFriend(this.markerId);
	},
	onShow() {
		if (this.markerId) {
		
			this.getUser(this.markerId);
		} else {
			this.showToast('用户ID不存在');
		}
	},
	methods: {
		formatMessageTime,
		/* 判断当前用户与目标用户是否为好友
		 * @param {string} targetUserId - 目标用户ID（必传）
		 * @returns {Promise<boolean>} - 是否为好友（true/false）
		 */
		async getIsFriend(targetUserId) {
			console.log('是否好友', targetUserId);

			// 1. 参数校验
			if (!targetUserId || typeof targetUserId !== 'string') {
				showToast({ title: '目标用户ID无效', icon: 'none' });
				return false; // 无效参数视为非好友
			}

			try {
				const userId = this.storeData.user.userId;
				// 2. 调用云对象接口
				const res = await friend.isFriend({ userId, targetUserId: targetUserId });
				if (res.success) {
					this.status = res.data.status;
					this.isFriend = res.data.isFriend;
				} else {
					this.isFriend = false;
				}
			} catch (e) {
				console.error('判断好友关系失败:', e);
				showToast({ title: e.message || '获取好友关系失败', icon: 'none' });
				this.isFriend = false;
			}
		},
		getDistance(loc1) {
			const loc = {
				longitude: loc1.coordinates[0],
				latitude: loc1.coordinates[1]
			};

			return distance_m(loc, this.storeData.location);
		},
		remarkName(){
			this.type="remarkName"
			this.maxLength=12
			this.placeholder="添加备注，不超过20个字"
			this.title="添加好友备主"
			this.isDialogShow=true
		},

		async getUser(id) {
			try {
				if (!id) {
					console.warn('非法', id);
				}
				const res = await getFriendUserInfo(id, this.storeData.user.userId,true);
				this.userInfo = res;
				console.log(this.userInfo);

				// 获取店铺信息
				const shopResult = await db
					.collection('sendshop')
					.where({
						sendUserId: id
					})
					.get();
				this.shopInfo = shopResult.data;
				console.log('shop', shopResult);
				// 获取商品信息
				const goodResult = await db
					.collection('sendgood')
					.where({
						senderUserId: id
					})
					.get();
				console.log('商品', goodResult);
				this.goodInfo = goodResult.data;
			} catch (e) {
				console.error('获取用户信息失败:', e);
				this.showToast('加载失败，请重试');
			} finally {
				// 隐藏加载中
				uni.hideLoading();
			}
		},
		async applyConfirm(e) {
			if(this.type==='remarkName'){
				this.handleRemarkName(e)
			}else if(this.type==="addFriend"){
				this.handleApplyFriend(e)
			}
			
			
		},
		async handleRemarkName(e){
			const userId=this.storeData.user.userId
			const friendUserId=this.markerId
			const remarkName=e
		const res=await	friend.editFriendRemarkName({userId,friendUserId,remarkName})
		if(res.success){
			this.remark=res.data.remarkName
		}else{
			uni.showToast({
				title:res.message,
				position:"center"
			})
		}
		},
		
		async handleApplyFriend (e){
			if (!this.markerId.trim()) {
				uni.showToast({ title: '请输入好友ID', icon: 'none' });
				return;
			}
			uni.showLoading({
				title: '申请中...'
			});
			try {
				const res = await friend.applyAddFriend({
					userId: this.storeData.user.userId,
					friendUserId: this.markerId.trim(),
					applyMsg: e.trim(),
					remarkName: ''
				});
			
				if (res.success) {
					const toTarget = {};
					toTarget.targetId = this.markerId;
					toTarget.targetType = '3';
					const msger = new MessageSender(this.storeData);
					try {
						const msg = await msger.sendApplyFriend(toTarget, e.trim());
						console.log('申请好友后', msg);
					} catch (e) {
						console.error(e);
					}
			
					uni.showToast({ title: '申请已发送，等待好友通过', position: 'center', duration: 2000 });
				}
				if (!res.success) {
					uni.showToast({
						title: res.message,
						position: 'center',
						duration: 2000
					});
				}
			} catch (err) {
				// 捕获错误（如重复申请、用户不存在等）
				uni.showToast({ title: err.message || '申请失败', position: 'center', icon: 'none' });
				console.error('申请好友失败：', err);
			} finally {
				uni.hideLoading();
			}
		},
		applyCancel() {
			this.dialogShow = false;
		},
		// 查看大图头像
		viewLargeAvatar() {
			const url = this.userInfo.nicPic || this.defaultAvatar;
			uni.previewImage({
				urls: [url],
				current: url
			});
		},

		async handleAddFriend() {
			this.placeholder='请添加附言'
			this.type="addFriend"
			this.title='好友申请'
			this.isDialogShow = true;
			this.applyMsg = `我是${this.storeData.user.nicName}请求您加为好友！`;
		},

		// 发送私聊
		handleSendMessage() {
			// 根据 relationStatus 判断状态
			switch (this.isFriend) {
				case 2:
					uni.showToast({
						title: '已拉黑，无法发送消息',
						icon: 'none',
						position: 'center'
					});
					break; // 必须加 break 防止穿透
				case 3:
					uni.showToast({
						title: '已删除好友，请重新添加',
						icon: 'none',
						position: 'center'
					});
					break;
				default:
					// 非拉黑或删除用户都可以发送消息，后台控制非好友的发送次数

					const queryParam = {
						id: this.userInfo.userId,
						type: 'person'
					};
					this.$store.commit('msg/SET_queryParam', queryParam);
					setToTarget('person', {
						targetId: this.userInfo.userId,
						nicName: this.userInfo.nicName,
						nicPic: this.userInfo.nicPic.url
					});
					uni.navigateTo({
						url: '/pages/messages/messages'
					});
			}
		},
		// 查看店铺详情
		viewShopDetail(shop) {
			uni.navigateTo({
				url: `/pages/shop/detail?id=${shop._id}`
			});
		},

		// 查看商品详情
		viewGoodDetail(good) {
			uni.navigateTo({
				url: `/pages/good/detail?id=${good._id}`
			});
		},

		// 导航到其他页面
		navigateTo(type) {
			switch (type) {
				case 'shops':
					uni.showToast({
						title: '好友还没有开店',
						position: 'center'
					});
					break;
				case 'goods':
					uni.showToast({
						title: '好友没有发布商品',
						position: 'center'
					});
					break;
				case 'fans':
					uni.showToast({
						title: '好友未公开粉丝',
						position: 'center'
					});
					break;
				case 'allShops':
					this.navigateTo('shops');
					break;
				case 'allGoods':
					this.navigateTo('goods');
					break;
			}
		}
	}
};
</script>

<style lang="scss">
.user-profile-page {
	background-color: #f5f7fa;
	min-height: 100vh;
	font-size: 14px;
}

/* 顶部背景与用户信息 */
.profile-header {
	position: relative;
	width: 100%;

	.header-bg {
		width: 100%;
		height: 200rpx;
		background-size: cover;
		background-position: center;
		filter: blur(2rpx);
	}

	.user-info-container {
		position: absolute;
		top: 100rpx;
		left: 0;
		width: 100%;
		padding: 0 30rpx;
		display: flex;
		box-sizing: border-box;
	}

	.nicpic {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		overflow: hidden;
		border: 4rpx solid #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		position: relative;

		.pic {
			width: 100%;
			height: 100%;
		}

		.online-indicator {
			position: absolute;
			right: 6rpx;
			bottom: 6rpx;
			width: 24rpx;
			height: 24rpx;
			border-radius: 50%;
			background-color: #00b42a;
			border: 2rpx solid #fff;
		}
	}

	.name-area {
		margin-left: 30rpx;
		background-color: rgba(255, 255, 255, 0.8);
		height: 80rpx;
		min-width: 200rpx;
		padding: 10rpx 25rpx;
		border-radius: 10rpx;

		.name-row {
			display: flex;
			align-items: center;

			.name {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}

			.friend-badge {
				margin-left: 16rpx;
				background-color: #52c41a;
				color: #fff;
				padding: 2rpx 14rpx;
				border-radius: 20rpx;
				font-size: 20rpx;

				.badge-text {
					color: #fff;
				}
			}
		}

		.userid {
			margin-top: 8rpx;
			font-size: 24rpx;
			color: #888;
		}

		.user-signature {
			margin-top: 12rpx;
			font-size: 26rpx;
			color: #666;
			line-height: 1.4;
			max-width: 500rpx;
			text-overflow: ellipsis;
			overflow: hidden;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
		}
	}
}

/* 统计数据 */
.stats-container {
	display: flex;
	justify-content: space-around;
	background-color: #fff;
	padding: 40rpx 0;
	margin-top: 80rpx;
	border-radius: 16rpx;
	margin: 80rpx 20rpx 0;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 10rpx 0;
		border-radius: 8rpx;
		transition: all 0.2s ease;
		width: 33.333%;

		&:active {
			background-color: #f5f5f5;
		}

		.stat-value {
			font-size: 36rpx;
			font-weight: 700;
			color: #333;
			margin-bottom: 6rpx;
		}

		.stat-label {
			font-size: 24rpx;
			color: #888;
		}
	}
}

/* 通用区块样式 */
.section {
	margin-top: 20rpx;
	background-color: #fff;
	padding: 24rpx 30rpx;

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;

		.section-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
		}

		.section-more {
			font-size: 26rpx;
			color: #1890ff;
			display: flex;
			align-items: center;

			&:after {
				content: '';
				display: inline-block;
				width: 14rpx;
				height: 14rpx;
				border-top: 2rpx solid #1890ff;
				border-right: 2rpx solid #1890ff;
				transform: rotate(45deg);
				margin-left: 8rpx;
			}
		}
	}

	.horizontal-scroll {
		width: 100%;
		white-space: nowrap;
		padding-bottom: 10rpx;

		.scroll-container {
			display: inline-flex;
			gap: 20rpx;
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;

		.empty-text {
			margin-top: 20rpx;
			font-size: 26rpx;
			color: #999;
		}
	}
}

/* 店铺样式 */
.shop-item {
	width: 280rpx;
	display: inline-block;
	background-color: #f9f9f9;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.2s ease;

	&:active {
		transform: scale(0.98);
	}

	.shop-img {
		width: 100%;
		height: 180rpx;
	}

	.shop-name {
		display: block;
		padding: 16rpx 16rpx 8rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.shop-desc {
		display: block;
		padding: 0 16rpx 16rpx;
		font-size: 22rpx;
		color: #666;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		line-height: 1.4;
		height: 62rpx;
	}
	.shop-sendInfo {
		display: flex;
		font-size: 22rpx;
	}
}

/* 商品样式 */
.good-item {
	width: 220rpx;
	display: inline-block;
	background-color: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.2s ease;
	vertical-align: top; /* 解决 inline-block 基线对齐导致的错位 */
	padding-bottom: 10rpx; /* 增加底部内边距，避免内容被截断 */

	&:active {
		transform: scale(0.98);
	}

	.good-img {
		width: 100%;
		height: 220rpx;
		display: block; /* 消除图片底部空白 */
	}

	.good-name {
		display: block;
		padding: 16rpx 16rpx 8rpx;
		font-size: 24rpx;
		color: #333;
		display: -webkit-box;
		-webkit-line-clamp: 2; /* 最多显示2行 */
		-webkit-box-orient: vertical;
		overflow: hidden;
		line-height: 1.4;
		/* 移除固定高度，让内容自适应（避免文字少的时候被截断） */
		/* height: 68rpx; */
		min-height: 68rpx; /* 改为最小高度，确保占位 */
	}

	.good-price {
		display: block;
		padding: 0 16rpx 8rpx; /* 减少底部内边距，避免超出容器 */
		font-size: 26rpx;
		color: #f5222d;
		font-weight: 600;
		white-space: nowrap; /* 防止价格换行 */
		overflow: hidden;
		text-overflow: ellipsis; /* 价格过长时显示省略号 */
	}
}

/* 按钮区域 */
.btnarea {
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	box-sizing: border-box;

	.action-btn {
		flex: 1;
		height: 90rpx;
		border-radius: 45rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 500;
		transition: all 0.2s ease;
		cursor: pointer;

		&:active {
			opacity: 0.8;
		}

		.btn-text {
			margin-left: 10rpx;
			color: #fff;
		}
	}

	.add-friend {
		background-color: #1890ff;
	}

	.has-friend {
		background-color: #52c41a;
	}

	.message {
		background-color: #faad14;
	}

	.disabled {
		background-color: #ccc;
		cursor: not-allowed;

		&:active {
			opacity: 1;
		}
	}

	.loading {
		opacity: 0.8;
	}
}

/* 适配底部安全区 */
@media (env(safe-area-inset-bottom)) {
	.btnarea {
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
	}
}
</style>
